import React from 'react';

import {Table, Icon, Dropdown, InputNumber, Menu, Row, Col, Button} from 'antd';
import {Link, withRouter} from 'react-router-dom'
import HttpUtils from "../../utils/HttpUtils";

class CartItems extends React.Component {
    tableProps = {
        bordered: false,
        loading: false,
        pagination: false,
        size: 'default',
        showHeader: true,
        scroll: undefined,
    }

    columns = [{
        title: '商品',
        dataIndex: 'name',
        key: 'name',
        width: 500,
        render: (text, record) => this.renderProduct(text, record),
    }, {
        title: '单价',
        dataIndex: 'age',
        key: 'age',
        width: 100,
        render: (text, record) => this.renderPrice(text, record)
    }, {
        title: '数量',
        dataIndex: 'address',
        key: 'address',
        width: 150,
        render: (text, record) => this.renderQuantity(text, record)
    }, {
        title: '小计',
        dataIndex: 'subtotal',
        key: 'subtotal',
        width: 100,
        render: (text, record) => this.renderSubtotal(text, record)
    }, {
        title: '操作',
        key: 'action',
        width: 200,
        render: (text, record) => this.renderOptions(text, record)
    }];

    state = {
        cart: {
            items: []
        },
        selectedRowKeys: [],
        rowKeys: []
    }

    constructor(props) {
        super(props)
        if (typeof props.getInstance === 'function') {
            props.getInstance(this)
        }
    }

    componentDidMount() {
        this.fetchCart();
    }

    fetchCart() {
        var self = this;
        HttpUtils.getMyCart({}, {
            success: function (resp) {
                self.setCart(resp.data)
            }, error: function (resp) {
                console.error(resp)
            }
        });
    }

    checkout() {
        this.props.history.push("/checkout")
        // let self = this;
        // let selectedProdIds = this.state.selectedRowKeys;
        // HttpUtils.checkout(selectedProdIds, {
        //     success: function (resp) {
        //         self.props.history.push("/checkout")
        //     },
        //     error: function (resp) {
        //
        //     }
        // })
    }

    setCart(cart) {
        let selectedRowKeys = [];
        let rowKeys = [];
        cart.items.map((item) => {
            rowKeys.push(item.prodId)
            if (item.isSelected) {
                selectedRowKeys.push(item.prodId)
            }
        })
        this.setState({cart, selectedRowKeys, rowKeys});
    }

    addItem(prodId) {
        let self = this;
        HttpUtils.addItem(prodId, {
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    removeItem(record) {
        let self = this;
        HttpUtils.removeItem(record.id, {
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    addToFavor(item , index) {
        console.info("addFavor=>" + item)
        console.info("addFavor=>" + index)
    }

    changeQuantity(record, quantity) {
        let self = this;
        HttpUtils.changeQuantity(record.prodId, quantity, {
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    changeSelectedItem (selectedRowKeys){
        if (selectedRowKeys.length === 0) {
            this.cancelAllItems();
            return;
        } else if (selectedRowKeys.length === this.state.rowKeys.length) {
            this.selectAllItems()
            return;
        } else {
            let addedProdId = selectedRowKeys.filter((key) => {
                return !this.state.selectedRowKeys.includes(key)
            })
            if(addedProdId.length > 0){
                this.selectItem(addedProdId)
            }
            let removedProdId = this.state.selectedRowKeys.filter((key) => {
                return !selectedRowKeys.includes(key)
            })
            if(removedProdId.length > 0){
                this.cancelItem(removedProdId)
            }
        }
        this.setState({selectedRowKeys});
    }

    selectItem(prodId){
        let self = this;
        HttpUtils.selectItem(prodId , {
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    cancelItem(prodId){
        let self = this;
        HttpUtils.cancelItem(prodId , {
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    selectAllItems() {
        let self = this;
        HttpUtils.selectAllItems({
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    cancelAllItems() {
        let self = this;
        HttpUtils.cancelAllItems({
            success(resp) {
                self.setCart(resp.data)
            }
        })
    }

    render() {
        let self = this;
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                self.changeSelectedItem(selectedRowKeys)
            },
        }
        return (
            <div>
                <Table {...this.tableProps} rowSelection={rowSelection} columns={this.columns}
                       dataSource={this.state.cart.items} rowKey='prodId'/>
                <div style={{'background': '#f4f4f4'}}>
                    <Row>
                        <Col span={6} offset={12}>
                            <span>已经选择： <span style={{color:'red'}}>{this.state.cart.selectedTotalAmount}</span>  件商品</span> <br/>
                        </Col>
                        <Col span={3}>
                            <span>总价：<span style={{color:'red'}}>¥{this.state.cart.totalPrice}</span></span> <br/>
                        </Col>
                        <Col span={3}>
                            <Button type="primary" size='large' className="pull-right" style={{'height': '60px'}}
                                    onClick={() => this.checkout()}>去结算</Button>
                        </Col>
                    </Row>
                </div>
            </div>
        );
    }

    renderProduct(text, record) {
        return (
            <div>
                <Col span={9}>
                    <Link to={'/product/' + record.prodId}>
                        <img width="120" src={record.prodImg}/>
                    </Link>
                </Col>
                <Col span={8}>
                    <Link to={'/product/' + record.prodId}>
                        <span className="ant-form-text" style={{fontSize: '14px'}}>{record.prodName}</span>
                    </Link>
                </Col>
                <Col span={7}>
                    {
                        record.specList
                        &&
                        record.specList.map((spec, index) => {
                            return (
                                <span className="ant-form-text"
                                      style={{
                                          fontSize: '10px',
                                          marginLeft: '10px',
                                          color: '#666'
                                      }}
                                      key={index}
                                >{spec.option}: {spec.value}</span>
                            )
                        })
                    }
                </Col>
            </div>
        );
    }

    renderPrice(text, record) {
        if (record.promotionList) {
            var menus = <Menu>
                {
                    record.promotionList.map((pmt , index) => {
                        return (
                            <Menu.Item key={index}>
                                <a href="javascript:void(0)">{pmt.name}</a>
                            </Menu.Item>
                        )
                    })
                }
            </Menu>
        }
        return (
            <div>
                <span className="ant-form-text">{record.price}</span><br/>
                {
                    record.promotionList &&
                    (
                        <Dropdown overlay={menus}>
                            <a href="javascript:void(0)">
                                促销 <Icon type="down"/>
                            </a>
                        </Dropdown>
                    )
                }
            </div>
        );
    }

    renderQuantity(text, record) {
        return (
            <InputNumber min={1} max={9999} defaultValue={record.quantity}
                         onChange={(e) => this.changeQuantity(record, e)}/>
        )
    }

    renderSubtotal(text, record) {
        return (
            <div>
                <span className="ant-form-text"
                      style={{
                          fontSize: '10px',
                          marginLeft: '10px',
                          color: '#666'
                      }}>¥{record.subTotal}</span><br/>
                {
                    record.weight
                    &&
                    (
                        <span className="ant-form-text"
                              style={{fontSize: '10px', marginLeft: '10px', color: '#666'}}>{record.weight}kg</span>
                    )
                }
            </div>
        )
    }

    renderOptions(text, record) {
        return (
            <div>
            <span>
              <a href="javascript:void(0)" onClick={() => this.removeItem(record)}>删除</a> <br/>
              <a href="javascript:void(0)" onClick={() => this.addToFavor(record)}>移到收藏栏</a>
            </span>
            </div>

        )
    }
}

/* 使用withRouter包装的组件， 父组件不能通过ref属性来获取到子组件 */
export default withRouter(CartItems);